package com.begamer.card.common.dao.hibernate;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.begamer.card.cache.PlayerInfo;
import com.begamer.card.common.Constant;
import com.begamer.card.common.util.StringUtil;
import com.begamer.card.common.util.binRead.NewPlayerData;
import com.begamer.card.common.util.binRead.RankRobotData;
import com.begamer.card.common.util.binRead.UniteskillrobotData;
import com.begamer.card.log.DbErrorLogger;
import com.begamer.card.model.pojo.Activity;
import com.begamer.card.model.pojo.Card;
import com.begamer.card.model.pojo.KopointLog;
import com.begamer.card.model.pojo.LotLog;
import com.begamer.card.model.pojo.ConsumeCrystalLog;
import com.begamer.card.model.pojo.Equip;
import com.begamer.card.model.pojo.Event;
import com.begamer.card.model.pojo.EventDrop;
import com.begamer.card.model.pojo.Formation;
import com.begamer.card.model.pojo.Friend;
import com.begamer.card.model.pojo.Item;
import com.begamer.card.model.pojo.LogBuy;
import com.begamer.card.model.pojo.LotRank;
import com.begamer.card.model.pojo.Mail;
import com.begamer.card.model.pojo.Maze;
import com.begamer.card.model.pojo.PassiveSkill;
import com.begamer.card.model.pojo.PayRecord;
import com.begamer.card.model.pojo.PkRank;
import com.begamer.card.model.pojo.Player;
import com.begamer.card.model.pojo.Skill;
import com.begamer.card.model.pojo.SpeciaMail;
import com.begamer.card.model.pojo.User;
import com.begamer.card.model.pojo.Var;
import com.begamer.card.model.pojo.ZcMail;

public class CommDao extends HibernateDaoSupport {
	private static final Logger dbLogger = DbErrorLogger.logger;
	private static final Logger logger = Logger.getLogger(CommDao.class);
	
	/**
	 * 获取一个玩家的所有信息 lt@2013-12-13 下午07:24:06
	 * 
	 * @param playerId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public PlayerInfo getPlayerInfo(int playerId)
	{
		Session session = getSession();
		try
		{
			// 获取player
			String hql = "from Player p where p.id=?";
			Query query = session.createQuery(hql);
			query.setInteger(0, playerId);
			List<Player> players = query.list();
			if (players.size() != 1)
			{
				return null;
			}
			Player player = players.get(0);
			// 获取card
			hql = "from Card c where c.playerId=? and c.sell=0";
			query = session.createQuery(hql);
			query.setInteger(0, playerId);
			List<Card> cards = query.list();
			// 获取skill
			hql = "from Skill s where s.playerId=? and s.sell=0";
			query = session.createQuery(hql);
			query.setInteger(0, playerId);
			List<Skill> skills = query.list();
			// 获取passiveSkill
			hql = "from PassiveSkill p where p.playerId=? and p.sell=0";
			query = session.createQuery(hql);
			query.setInteger(0, playerId);
			List<PassiveSkill> passiveSkills = query.list();
			// 获取equip
			hql = "from Equip e where e.playerId=? and e.sell=0";
			query = session.createQuery(hql);
			query.setInteger(0, playerId);
			List<Equip> equips = query.list();
			// 获取item
			hql = "from Item i where i.playerId=? and i.sell=0";
			query = session.createQuery(hql);
			query.setInteger(0, playerId);
			List<Item> items = query.list();
			// 获取formation
			hql = "from Formation f where f.playerId=?";
			query = session.createQuery(hql);
			query.setInteger(0, playerId);
			List<Formation> formations = query.list();
			// 获取friendIds
			hql = "from Friend f where f.playerId=? and f.state!=1";
			query = session.createQuery(hql);
			query.setInteger(0, playerId);
			List<Friend> friendIds = query.list();
			// 获取mails
			hql = "from Mail m where m.playerId=? and m.state!=1 order by m.sendTime DESC";
			query = session.createQuery(hql);
			query.setInteger(0, playerId);
			List<Mail> mails = query.list();
			//获取迷宫进度
			hql = "from Maze m where m.playerId=?";
			query = session.createQuery(hql);
			query.setInteger(0, playerId);
			List<Maze> mazes = query.list();
			return new PlayerInfo(player, cards, skills, passiveSkills, equips, items, formations.get(0), friendIds, mails,mazes);
		}
		catch (Exception e)
		{
			dbLogger.error("查询playerinfo出错,playerId:" + playerId, e);
		}
		finally
		{
			if(null != session){
				session.close();
			}		
		}
		return null;
	}
	
	/**
	 * 保存一个玩家的所有信息 lt@2013-12-13 下午07:23:51
	 * 
	 * @param pi
	 * @return
	 */
	public boolean savePlayerInfo(PlayerInfo pi)
	{
		pi.build();
		logger.info("save " + pi.player.getId());
		Session session = getSession();
		Transaction ts = session.beginTransaction();
		try
		{
			session.saveOrUpdate(pi.player);
			logger.info("save player completed");
			List<Maze> mazes = pi.getMazes();
			if (mazes!=null && mazes.size()>0)
			{
				for (Maze maze : mazes)
				{
					session.saveOrUpdate(maze);
				}
				logger.info("save maze completed");
			}
			List<Card> cards = pi.getAllCards();
			for (Card c : cards)
			{
				session.saveOrUpdate(c);
			}
			// 删除无用的内存数据
			for (int k = cards.size() - 1; k >= 0; k--)
			{
				Card c = cards.get(k);
				if (c.getSell() != 0)
				{
					cards.remove(k);
					c = null;
				}
			}
			logger.info("save card completed");
			
			List<Skill> skills = pi.getAllSkills();
			for (Skill s : skills)
			{
				session.saveOrUpdate(s);
			}
			// 删除无用的内存数据
			for (int k = skills.size() - 1; k >= 0; k--)
			{
				Skill s = skills.get(k);
				if (s.getSell() != 0)
				{
					skills.remove(k);
					s = null;
				}
			}
			logger.info("save skill completed");
			
			List<PassiveSkill> pSkills = pi.getAllPassiveSkills();
			for (PassiveSkill p : pSkills)
			{
				session.saveOrUpdate(p);
			}
			// 删除无用的内存数据
			for (int k = pSkills.size() - 1; k >= 0; k--)
			{
				PassiveSkill p = pSkills.get(k);
				if (p.getSell() != 0)
				{
					pSkills.remove(k);
					p = null;
				}
			}
			logger.info("save passiveSkill completed");
			
			List<Equip> equips = pi.getAllEquips();
			for (Equip e : equips)
			{
				session.saveOrUpdate(e);
			}
			// 删除无用的内存数据
			for (int k = equips.size() - 1; k >= 0; k--)
			{
				Equip e = equips.get(k);
				if (e.getSell() != 0)
				{
					equips.remove(k);
					e = null;
				}
			}
			logger.info("save equip completed");
			
			List<Item> items = pi.getAllItems();
			for (Item i : items)
			{
				session.saveOrUpdate(i);
			}
			// 删除无用的内存数据
			for (int k = items.size() - 1; k >= 0; k--)
			{
				Item item = items.get(k);
				if (item.getSell() != 0)
				{
					items.remove(k);
					item = null;
				}
			}
			logger.info("save item completed");
			
			session.saveOrUpdate(pi.getFormation());
			logger.info("save formation completed");
			
			ts.commit();
			logger.info("save " + pi.player.getId() + " completed");
		}
		catch (Exception e)
		{
			dbLogger.error("保存playerInfo出错:" + pi.player.getId(), e);
			ts.rollback();
		}
		finally
		{
			session.close();
		}
		
		Session session2 = getSession();
		Transaction ts2 = session2.beginTransaction();
		try
		{
			List<Friend> friends = pi.getAllFriends();
			for (Friend f : friends)
			{
				session2.saveOrUpdate(f);
			}
			// 删除无用的内存数据
			for (int k = friends.size() - 1; k >= 0; k--)
			{
				Friend f = friends.get(k);
				if (f.getState() == 1)
				{
					friends.remove(k);
					f = null;
				}
			}
			ts2.commit();
			logger.info("save friend completed");
		}
		catch (Exception e)
		{
			dbLogger.error("保存playerInfo出错:" + pi.player.getId(), e);
			ts2.rollback();
		}
		finally
		{
			session2.close();
		}
		
		Session session3 = getSession();
		Transaction ts3 = session3.beginTransaction();
		try
		{
			List<Mail> mails = pi.getAllMails();
			for (Mail m : mails)
			{
				session3.saveOrUpdate(m);
			}
			// 删除无用的内存数据
			for (int k = mails.size() - 1; k >= 0; k--)
			{
				Mail m = mails.get(k);
				if (m.getState() == 1)
				{
					mails.remove(k);
				}
			}
			ts3.commit();
			logger.info("save mail completed");
		}
		catch (Exception e)
		{
			dbLogger.error("保存playerInfo出错:" + pi.player.getId(), e);
			ts3.rollback();
		}
		finally
		{
			session3.close();
		}
		
		return true;
	}
	
	public String deletePlayerInfo()
	{
		Session session = getSession();
		Transaction ts = session.beginTransaction();
		String msg = null;
		try
		{
			// 删除card
			String hql = "delete Card where sell !=0";
			Query query = session.createQuery(hql);
			int card = query.executeUpdate();
			// 删除equip
			hql = "delete Equip where sell!=0";
			query = session.createQuery(hql);
			int equip = query.executeUpdate();
			// 删除item
			hql = "delete Item where sell!=0";
			query = session.createQuery(hql);
			int item = query.executeUpdate();
			// 删除passiveSkill
			hql = "delete PassiveSkill where sell!=0";
			query = session.createQuery(hql);
			int passiveSkill = query.executeUpdate();
			// 删除skill
			hql = "delete Skill where sell!=0";
			query = session.createQuery(hql);
			int skill = query.executeUpdate();
			// 删除friend
			hql = "delete Friend where state=1";
			query = session.createQuery(hql);
			int friend = query.executeUpdate();
			// 删除mail
			hql = "delete Mail where state=1";
			query = session.createQuery(hql);
			int mail = query.executeUpdate();
			ts.commit();
			msg = "card-equip-item-passiveskill-skill-friend:" + card + "-" + equip + "-" + item + "-" + passiveSkill + "-" + skill + "-" + friend + "-" + mail;
		}
		catch (Exception e)
		{
			ts.rollback();
			dbLogger.error("删除无效数据出错", e);
		}
		finally
		{
			session.close();
		}
		return msg;
	}
	
	@SuppressWarnings("unchecked")
	public int getPlayerIdByUserId(int userId)
	{
		Session session = getSession();
		try
		{
			String hql = "from Player p where p.userId=?";
			Query query = session.createQuery(hql);
			query.setInteger(0, userId);
			List<Player> players = query.list();
			if (players.size() == 1)
			{
				return players.get(0).getId();
			}
		}
		catch (Exception e)
		{
			dbLogger.error("查找玩家出错", e);
		}
		finally
		{
			session.close();
		}
		return 0;
	}
	
	@SuppressWarnings("unchecked")
	public List<Friend> getFriends(int playerId)
	{
		Session session = getSession();
		try
		{
			Query query = session.createQuery("from Friend f where f.playerId=?");
			query.setInteger(0, playerId);
			return query.list();
		}
		catch (Exception e)
		{
			dbLogger.error("获取好友数据出错" + playerId, e);
		}
		finally
		{
			session.close();
		}
		return null;
	}
	
	/** 获取playerId,level,icon **/
	@SuppressWarnings("deprecation")
	public HashMap<Integer, String> getPlayerTemps()
	{
		HashMap<Integer, String> result = new HashMap<Integer, String>();
		Session session = getSession();
		try
		{
			String sql = "select ID,LEVEL,ICONID from player";
			Connection conn = session.connection();
			PreparedStatement ps = conn.prepareStatement(sql);
			ResultSet rs = ps.executeQuery();
			while (rs.next())
			{
				result.put(rs.getInt("ID"), rs.getInt("LEVEL") + "-" + rs.getInt("ICONID"));
			}
			conn.close();
		}
		catch (Exception e)
		{
			dbLogger.error("查找玩家等级合体技出错", e);
		}
		finally
		{
			session.close();
		}
		return result;
	}
	
	/** 获取playerId-level **/
	@SuppressWarnings("deprecation")
	public List<Integer> getPlayerIdsForInitRank(int minLevel)
	{
		List<Integer> result = new ArrayList<Integer>();
		Session session = getSession();
		try
		{
			String sql = "select ID from player where LEVEL>=?";
			Connection conn = session.connection();
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setInt(1, minLevel);
			ResultSet rs = ps.executeQuery();
			while (rs.next())
			{
				result.add(rs.getInt("ID"));
			}
			rs.close();
			ps.close();
			conn.close();
		}
		catch (Exception e)
		{
			dbLogger.error("查找玩家等级出错", e);
		}
		finally
		{
			session.close();
		}
		return result;
	}
	
	/** 获取playerId-level **/
	@SuppressWarnings("deprecation")
	public List<Integer> getPlayerIds(int minLevel)
	{
		List<Integer> result = new ArrayList<Integer>();
		Session session = getSession();
		try
		{
			String sql = "select ID from player where LEVEL>=? AND USERID>0";
			Connection conn = session.connection();
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setInt(1, minLevel);
			ResultSet rs = ps.executeQuery();
			while (rs.next())
			{
				result.add(rs.getInt("ID"));
			}
			rs.close();
			ps.close();
			conn.close();
		}
		catch (Exception e)
		{
			dbLogger.error("查找玩家等级出错", e);
		}
		finally
		{
			session.close();
		}
		return result;
	}
	
	@SuppressWarnings("unchecked")
	public Player getPlayer(int playerId)
	{
		Session session = getSession();
		try
		{
			String hql = "from Player p where p.id=?";
			Query query = session.createQuery(hql);
			query.setInteger(0, playerId);
			List<Player> players = query.list();
			if (players.size() >= 1)
			{
				return players.get(0);
			}
		}
		catch (Exception e)
		{
			dbLogger.error("查找玩家出错", e);
		}
		finally
		{
			session.close();
		}
		return null;
	}
	
	@SuppressWarnings("unchecked")
	public Player getPlayer(String name)
	{
		Session session = getSession();
		try
		{
			String hql = "from Player p where p.name=?";
			Query query = session.createQuery(hql);
			query.setString(0, name.trim());
			List<Player> players = query.list();
			if (players.size() >= 1)
			{
				return players.get(0);
			}
		}
		catch (Exception e)
		{
			dbLogger.error("查找玩家出错2", e);
		}
		finally
		{
			session.close();
		}
		return null;
	}
	
	/** 获取好友个数 **/
	public int getFriendNum(int playerId)
	{
		Session session = getSession();
		try
		{
			Query query = session.createQuery("from Friend f where f.playerId=?");
			query.setInteger(0, playerId);
			return query.list().size();
		}
		catch (Exception e)
		{
			dbLogger.error("查询好友个数出错", e);
		}
		finally
		{
			session.close();
		}
		return 0;
	}
	
	/** 保存好友 **/
	public void saveFriend(Friend f)
	{
		Session session = getSession();
		Transaction ts = session.beginTransaction();
		try
		{
			session.save(f);
			ts.commit();
		}
		catch (Exception e)
		{
			dbLogger.error("保存好友出错", e);
			ts.rollback();
		}
		finally
		{
			session.close();
		}
	}
	
	/** 删除好友 **/
	@SuppressWarnings("unchecked")
	public void removeFriend(int playerId, int friendId)
	{
		Session session = getSession();
		Transaction ts = session.beginTransaction();
		try
		{
			Query query = session.createQuery("from Friend f where f.playerId=? and f.friendId=?");
			// Query
			// query=session.createQuery("update Friend f set f.state=1 where f.playerId=? and f.friendId=?");
			query.setInteger(0, playerId);
			query.setInteger(1, friendId);
			List<Friend> list = query.list();
			if (list != null && list.size() > 0)
			{
				Friend f = list.get(0);
				f.setState(1);
				session.saveOrUpdate(f);
			}
			ts.commit();
		}
		catch (Exception e)
		{
			dbLogger.error("删除好友出错", e);
			ts.rollback();
		}
		finally
		{
			session.close();
		}
	}
	
	@SuppressWarnings("unchecked")
	public void updateFriend(int playerId, int friendId, List<String> states)
	{
		List<Friend> friends = new ArrayList<Friend>();
		Session session = getSession();
		Transaction ts = session.beginTransaction();
		try
		{
			for (String s : states)
			{
				String[] ss = s.split("-");
				int oldState = StringUtil.getInt(ss[0]);
				int newState = StringUtil.getInt(ss[1]);
				Query query = session.createQuery("from Friend f where f.playerId=? and f.friendId=? and f.state=?");
				// Query
				// query=session.createQuery("update Friend f set f.state=? where f.playerId=? and f.friendId=? and f.state=?");
				query.setInteger(0, playerId);
				query.setInteger(1, friendId);
				query.setInteger(2, oldState);
				// query.setInteger(3, oldState);
				// query.executeUpdate();
				List<Friend> list = query.list();
				if (list != null && list.size() > 0)
				{
					Friend f = list.get(0);
					f.setState(newState);
					friends.add(f);
				}
			}
			for (Friend f : friends)
			{
				session.saveOrUpdate(f);
			}
			ts.commit();
		}
		catch (Exception e)
		{
			dbLogger.error("更新好友出错", e);
			ts.rollback();
		}
		finally
		{
			session.close();
		}
	}
	
	@SuppressWarnings("unchecked")
	/**获取pkrank信息，加载至缓存**/
	public List<PkRank> getPkRanks()
	{
		Session session = getSession();
		try
		{
			// 获取pkrank
			String hql = "from PkRank pr";
			Query query = session.createQuery(hql);
			List<PkRank> pkRanks = query.list();
			if (pkRanks.size() <= 0)
			{
				return null;
			}
			else
			{
				return pkRanks;
			}
		}
		catch (Exception e)
		{
			dbLogger.error("查询pkrank出错,playerId:", e);
		}
		finally
		{
			session.close();
		}
		return null;
	}
	
	/** 保存pkrank信息 **/
	public void savePkRank(PkRank pr)
	{
		Session session = getSession();
		Transaction ts = session.beginTransaction();
		try
		{
			session.saveOrUpdate(pr);
			logger.info("save pr completed");
			ts.commit();
		}
		catch (Exception e)
		{
			dbLogger.error("保存pk排名出错", e);
			ts.rollback();
		}
		finally
		{
			session.close();
		}
	}
	
	/** 保存pkrank信息 **/
	public void savePkRanks(Collection<PkRank> prs)
	{
		Session session = getSession();
		Transaction ts = session.beginTransaction();
		try
		{
			for (PkRank pr : prs)
			{
				session.saveOrUpdate(pr);
			}
			logger.info("save prs completed");
			ts.commit();
		}
		catch (Exception e)
		{
			dbLogger.error("保存pks排名出错", e);
			ts.rollback();
		}
		finally
		{
			session.close();
		}
	}
	
	@SuppressWarnings("unchecked")
	/**根据playerid查找玩家的排名**/
	public PkRank getPkRankByPlayer(int playerId)
	{
		Session session = getSession();
		try
		{
			String hql = "from PkRank pr where pr.playerId=?";
			Query query = session.createQuery(hql);
			query.setInteger(0, playerId);
			List<PkRank> pkranks = query.list();
			if (pkranks.size() >= 1)
			{
				return pkranks.get(0);
			}
		}
		catch (Exception e)
		{
			dbLogger.error("查找pkrank出错", e);
		}
		finally
		{
			session.close();
		}
		return null;
	}
	
	/** 返回playerId **/
	public void regUniteskillrobotPlayers(List<UniteskillrobotData> list)
	{
		Session session = getSession();
		Transaction ts = session.beginTransaction();
		try
		{
			String lastLogin = StringUtil.getDateTime(System.currentTimeMillis());
			for (UniteskillrobotData ud : list)
			{
				// save player
				Player player = new Player();
				player.setUserId(0);
				player.setLastLogin(lastLogin);
				player.setName(ud.name);
				player.setHead("card042");
				player.setLevel(ud.level);
				player.setCurExp(0);
				player.setExtendCardNum(0);
				player.setGold(0);
				player.setCrystal(0);
				player.setMissionId(0);
				player.setCompleteStar1("");
				player.setBouns1("");
				player.setTimes1("00");// 两位字符来表示进入次数
				player.setMissionId2(0);
				player.setCompleteStar2("");
				player.setBouns2("");
				player.setTimes2("");
				player.setIconId(ud.uniteskill);
				player.setFriend(0);
				player.setLuckyNum(0);
				player.setLoginDayNum(1);
				player.setMaze("");
				player.setPower(0);
				player.setRuneNum(0);
				player.setRuneId("1-0-0-0-0-0-0");
				player.setRuneProAdd("0-0-0-0-0-0");
				player.setLastZeroDate(StringUtil.getDate(System.currentTimeMillis()));
				player.setImagination(1);
				player.setLastRestorePowerTime(System.currentTimeMillis());
				player.setFBnum1("");
				player.setFBnum2("");
				player.setAchive("0%1");
				player.setNewPlayerType(100);
				player.setMaxEnergy(Constant.InitMaxEnergy);
				player.setVipLevel(0);
				player.setVipCost(0);
				player.setVipMonthDay(0);
				player.setVipMonthType(0);
				player.setBattlePower(ud.power);
				player.setChangeNameTime(0);
				player.setBuyGoldTimes(0);
				player.setBuyPowerTimes(0);
				player.setHeadIconUnlock(1);
				player.setBuyPveEntryTimes1("00");
				player.setBuyPveEntryTimes2("");
				player.setMazeFirstEntry("");
				player.setCompose("");
				player.setDailyTaskComplete("");
				player.setDailyTaskState("");
				player.setKopoint(0);
				player.setKoExchange("");
				player.setBuyVipGift("");
				player.setBuyShopBoxNum(0);
				player.setBuyShopNum("");
				player.setBuyShopNums("");
				player.setBuyRefreshTimes(0);
				player.setAllSelectId("");
				player.setLotPort(0);
				player.setFirstLot(0);
				player.setSignTimes(0);
				player.setLastSignTime("");
				player.setBuyPkCdTimes(0);
				player.setBuyPkNumTimes(0);
				player.setLastMissionId(0);
				player.setLastResponseTime(StringUtil.getDate(System.currentTimeMillis()));
				player.setLogoutTime("");
				player.setInviteFriendTimes(0);
				player.setComposeEquipTimes(0);
				player.setLineGift("");
				player.setBuyFriendTimes(0);
				player.setBuyBagTimes(0);
				player.setExchange("");
				player.setBlackMarketRefreshTime("");
				player.setBlackMarkets("");
				player.setLineGiftTime(StringUtil.getDateTime(System.currentTimeMillis()));
				player.setLoginDayAward("");
				player.setLevelgift("");
				player.setCornucopia(0);
				player.setOwncards("43002");
				player.setUnitskills("");
				player.setCornucopiaMail(0);
				player.setSackFirst(0);
				player.setCornucopiaCrystal(0);
				player.setBattlepowerSpeciamail("");
				player.setKopointSpeciamail("");
				player.setFirstPayType(0);
				player.setBloodBuffNum(0);
				player.setMazeBossDrop("");
				player.setMazeWish("");
				player.setActive(0);
				player.setActiveState("");
				
				player.setLottoReward("");
				player.setLottoTimes("");
				player.setLottoTurnTimes("");
				player.setLastLottoAward("");
				session.save(player);
				// save card
				String cardInfo = "";
				int k = 0;
				for (int i = 0; i < ud.cards.length; i++)
				{
					int cardId = ud.cards[i];
					if (cardId == 0)
					{
						cardInfo += "n-";
						continue;
					}
					cardInfo += k + "-";
					k++;
					Card c = Card.createCard(player.getId(), cardId, ud.level);
					session.save(c);
				}
				if (!"".equals(cardInfo))
				{
					cardInfo = cardInfo.substring(0, cardInfo.length() - 1);
				}
				// save formation
				Formation f = new Formation();
				f.setPlayerId(player.getId());
				f.setCardInfo(cardInfo);
				f.setSkillInfo("n-n-n-n-n-n");
				f.setPassiveSkillInfo("n-n-n-n-n-n");
				f.setEquipInfo("n-n-n-n-n-n");
				f.setUnitSkillInfo(ud.uniteskill);
				session.save(f);
			}
			ts.commit();
		}
		catch (Exception e)
		{
			ts.rollback();
			dbLogger.error("注册机器人出错,ud", e);
		}
		finally
		{
			session.close();
		}
	}
	
	/** 返回playerId **/
	public void regRankRobotPlayers(List<RankRobotData> list)
	{
		Session session = getSession();
		Transaction ts = session.beginTransaction();
		try
		{
			String lastLogin = StringUtil.getDateTime(System.currentTimeMillis());
			for (RankRobotData rrd : list)
			{
				// save player
				Player player = new Player();
				player.setUserId(0);
				player.setLastLogin(lastLogin);
				player.setName(rrd.name);
				player.setHead(rrd.icon);
				player.setLevel(rrd.level);
				player.setCurExp(0);
				player.setExtendCardNum(0);
				player.setGold(0);
				player.setCrystal(0);
				player.setMissionId(0);
				player.setCompleteStar1("");
				player.setBouns1("");
				player.setTimes1("00");// 两位字符来表示进入次数
				player.setMissionId2(0);
				player.setCompleteStar2("");
				player.setBouns2("");
				player.setTimes2("");
				player.setIconId(rrd.getUnitSkillId());
				player.setFriend(0);
				player.setLuckyNum(0);
				player.setLoginDayNum(1);
				player.setMaze("");
				player.setPower(0);
				player.setRuneNum(0);
				player.setRuneId("1-0-0-0-0-0-0");
				player.setRuneProAdd("0-0-0-0-0-0");
				player.setLastZeroDate(StringUtil.getDate(System.currentTimeMillis()));
				player.setImagination(1);
				player.setLastRestorePowerTime(System.currentTimeMillis());
				player.setFBnum1("");
				player.setFBnum2("");
				player.setAchive("0%1");
				player.setNewPlayerType(100);
				player.setMaxEnergy(Constant.InitMaxEnergy);
				player.setVipLevel(0);
				player.setVipCost(0);
				player.setVipMonthDay(0);
				player.setVipMonthType(0);
				player.setBattlePower(rrd.power);
				player.setChangeNameTime(0);
				player.setBuyGoldTimes(0);
				player.setBuyPowerTimes(0);
				player.setHeadIconUnlock(1);
				player.setBuyPveEntryTimes1("00");
				player.setBuyPveEntryTimes2("");
				player.setMazeFirstEntry("");
				player.setCompose("");
				player.setDailyTaskComplete("");
				player.setDailyTaskState("");
				player.setKopoint(0);
				player.setKoExchange("");
				player.setBuyVipGift("");
				player.setBuyShopBoxNum(0);
				player.setBuyShopNum("");
				player.setBuyShopNums("");
				player.setBuyRefreshTimes(0);
				player.setAllSelectId("");
				player.setLotPort(0);
				player.setFirstLot(0);
				player.setSignTimes(0);
				player.setLastSignTime("");
				player.setBuyPkNumTimes(0);
				player.setBuyPkCdTimes(0);
				player.setLastMissionId(0);
				player.setLastResponseTime(StringUtil.getDateTime(System.currentTimeMillis()));
				player.setLogoutTime("");
				player.setInviteFriendTimes(0);
				player.setComposeEquipTimes(0);
				player.setLineGift("");
				player.setBuyFriendTimes(0);
				player.setBuyBagTimes(0);
				player.setExchange("");
				player.setBlackMarketRefreshTime("");
				player.setBlackMarkets("");
				player.setLineGiftTime(StringUtil.getDateTime(System.currentTimeMillis()));
				player.setLoginDayAward("");
				player.setLevelgift("");
				player.setCornucopia(0);
				player.setOwncards("43002");
				player.setUnitskills("");
				player.setCornucopiaMail(0);
				player.setSackFirst(0);
				player.setCornucopiaCrystal(0);
				player.setBattlepowerSpeciamail("");
				player.setKopointSpeciamail("");
				player.setFirstPayType(0);
				player.setBloodBuffNum(0);
				player.setMazeBossDrop("");
				player.setMazeWish("");
				player.setActive(0);
				player.setActiveState("");
				
				player.setLottoReward("");
				player.setLottoTimes("");
				player.setLottoTurnTimes("");
				player.setLastLottoAward("");
				session.save(player);
				// save card
				String cardInfo = "";
				int k = 0;
				for (int i = 0; i < rrd.cards.length; i++)
				{
					String[] ss = rrd.cards[i].split("-");
					int cardId = StringUtil.getInt(ss[0]);
					int level = StringUtil.getInt(ss[1]);
					if (cardId == 0 || level == 0)
					{
						cardInfo += "n-";
						continue;
					}
					cardInfo += k + "-";
					k++;
					Card c = Card.createCard(player.getId(), cardId, level);
					session.save(c);
				}
				if (!"".equals(cardInfo))
				{
					cardInfo = cardInfo.substring(0, cardInfo.length() - 1);
				}
				// save formation
				Formation f = new Formation();
				f.setPlayerId(player.getId());
				f.setCardInfo(cardInfo);
				f.setSkillInfo("n-n-n-n-n-n");
				f.setPassiveSkillInfo("n-n-n-n-n-n");
				f.setEquipInfo("n-n-n-n-n-n");
				f.setUnitSkillInfo(rrd.getUnitSkillId());
				session.save(f);
			}
			ts.commit();
		}
		catch (Exception e)
		{
			ts.rollback();
			dbLogger.error("注册机器人出错,rrd", e);
		}
		finally
		{
			session.close();
		}
	}
	
	/** 返回playerId **/
	public int reg(String uid, String psd, String nickname, String ip, String platform)
	{
		Session session = getSession();
		Transaction ts = session.beginTransaction();
		try
		{
			User user = new User();
			user.setName(uid);
			user.setPassword(psd);
			user.setNickname(nickname);
			user.setPlatform(platform);
			user.setCreateOn(StringUtil.getNow());
			user.setUpdateOn(StringUtil.getNow());
			user.setIp(ip);
			session.save(user);
			
			String lastLogin = StringUtil.getDateTime(System.currentTimeMillis());
			int userId = user.getId();
			// 初始化player所有字段
			Player player = new Player();
			player.setUserId(userId);
			player.setPlatform(platform);
			player.setLastLogin(lastLogin);
			player.setName(nickname);
			player.setHead("card042");
			player.setLevel(1);
			player.setCurExp(0);
			player.setExtendCardNum(0);
			player.setGold(0);
			player.setCrystal(0);
			player.setLotPort(0);
			player.setMissionId(0);
			player.setCompleteStar1("");
			player.setBouns1("");
			player.setTimes1("00");// 两位字符来表示进入次数
			player.setMissionId2(0);
			player.setCompleteStar2("");
			player.setBouns2("");
			player.setTimes2("");
			player.setIconId(0);
			player.setFriend(0);
			player.setLuckyNum(0);
			player.setLoginDayNum(1);
			player.setMaze("");
			player.setPower(0);
			player.setRuneNum(0);
			player.setRuneId("1-0-0-0-0-0-0");
			player.setRuneProAdd("0-0-0-0-0-0");
			player.setLastZeroDate(StringUtil.getDate(System.currentTimeMillis()));
			player.setImagination(1);
			player.setLastRestorePowerTime(System.currentTimeMillis());
			player.setFBnum1("");
			player.setFBnum2("");
			player.setAchive("0%1");
			player.setNewPlayerType(0);
			player.setMaxEnergy(Constant.InitMaxEnergy);
			player.setVipLevel(0);
			player.setVipCost(0);
			player.setVipMonthDay(0);
			player.setVipMonthType(0);
			player.setBuyGoldTimes(0);
			player.setBuyPowerTimes(0);
			player.setHeadIconUnlock(1);
			player.setChangeNameTime(0);
			player.setBuyPveEntryTimes1("00");
			player.setBuyPveEntryTimes2("");
			player.setBuyPkCdTimes(0);
			player.setBuyPkNumTimes(0);
			player.setMazeFirstEntry("");
			player.setCompose("");
			player.setDailyTaskComplete("");
			player.setDailyTaskState("");
			player.setComposeEquipTimes(0);
			player.setKopoint(0);
			player.setKoExchange("");
			player.setLastResponseTime(StringUtil.getDateTime(System.currentTimeMillis()));
			player.setBuyFriendTimes(0);
			player.setBuyBagTimes(0);
			player.setBuyVipGift("");
			player.setBuyShopBoxNum(0);
			player.setBuyShopNum("");
			player.setBuyShopNums("");
			player.setBuyRefreshTimes(0);
			player.setAllSelectId("");
			player.setLineGift("");
			player.setFirstLot(0);
			player.setBattlePower(0);
			player.setSignTimes(0);
			player.setLastSignTime("");
			player.setLastMissionId(0);
			player.setLogoutTime("");
			player.setInviteFriendTimes(0);
			player.setExchange("");
			player.setBlackMarketRefreshTime("");
			player.setBlackMarkets("");
			player.setLineGiftTime(StringUtil.getDateTime(System.currentTimeMillis()));
			player.setLoginDayAward("");
			player.setLevelgift("");
			player.setCornucopia(0);
			player.setOwncards("43002");
			player.setUnitskills("");
			player.setCornucopiaMail(0);
			player.setSackFirst(0);
			player.setCornucopiaCrystal(0);
			player.setBattlepowerSpeciamail("");
			player.setKopointSpeciamail("");
			player.setFirstPayType(0);
			player.setBloodBuffNum(0);
			player.setMazeBossDrop("");
			player.setMazeWish("");
			player.setActive(0);
			player.setActiveState("");
			// test
			
			player.setLottoReward("");
			player.setLottoTimes("");
			player.setLottoTurnTimes("");
			player.setLastLottoAward("");
			player.setMnum(0);
			player.setMid(0);
			player.setMrandom(1);
			//test
			player.setRuneNum(3000);
			player.setPower(Constant.MaxPower);
			
			session.save(player);
			
			List<NewPlayerData> list = NewPlayerData.getAllNewPlayerData();
			int cardIndex = 0;
			int skillIndex = 0;
			int passiveSkillIndex = 0;
			Formation f = new Formation();
			f.setPlayerId(player.getId());
			f.setCardInfo("n-n-n-n-n-n");
			f.setSkillInfo("n-n-n-n-n-n");
			f.setPassiveSkillInfo("n-n-n-n-n-n");
			f.setEquipInfo("n-n-n-n-n-n");
			f.setUnitSkillInfo(0);
			for (NewPlayerData data : list)
			{
				if (data != null)
				{
					switch (data.type)
					{
						case 1:// 卡牌
							Card c = Card.createCard(player.getId(), data.goodId, 1);
							c.setNewType(1);
							session.save(c);
							
							if (data.position != 0)
							{
								String cardInfo = f.getCardInfo();
								String[] strs = cardInfo.split("-");
								strs[data.position - 1] = cardIndex + "";
								String temp = "";
								for (int k = 0; k < strs.length; k++)
								{
									temp += strs[k] + "-";
								}
								temp = temp.substring(0, temp.length() - 1);
								f.setCardInfo(temp);
								cardIndex++;
							}
							break;
						case 2:// 主动技能
							Skill s = Skill.createSkill(player.getId(), data.goodId, 1);
							s.setNewType(1);
							session.save(s);
							
							if (data.position != 0)
							{
								String skillInfo = f.getSkillInfo();
								String[] strs = skillInfo.split("-");
								strs[data.position - 1] = skillIndex + "";
								String temp = "";
								for (int k = 0; k < strs.length; k++)
								{
									temp += strs[k] + "-";
								}
								temp = temp.substring(0, temp.length() - 1);
								f.setSkillInfo(temp);
								skillIndex++;
							}
							break;
						case 3:// 被动技能
							PassiveSkill ps = PassiveSkill.createPassiveSkill(player.getId(), data.goodId);
							ps.setNewType(1);
							session.save(ps);
							
							if (data.position != 0)
							{
								String passiveSkillInfo = f.getPassiveSkillInfo();
								String[] strs = passiveSkillInfo.split("-");
								strs[data.position - 1] = passiveSkillIndex + "";
								String temp = "";
								for (int k = 0; k < strs.length; k++)
								{
									temp += strs[k] + "-";
								}
								temp = temp.substring(0, temp.length() - 1);
								f.setPassiveSkillInfo(temp);
								passiveSkillIndex++;
							}
							break;
						case 4:// 装备
							Equip equip = Equip.createEquip(player.getId(), data.goodId);
							equip.setNewType(1);
							session.save(equip);
							break;
						case 5:// 金币
							player.setGold(data.goodId);
							break;
						case 6:// 水晶
							player.setCrystal(data.goodId);
							break;
						case 7:// item
							Item item = Item.createItem(player.getId(), data.goodId, 1);
							item.setNewType(1);
							session.save(item);
							break;
					}
				}
			}
			// save formation
			session.save(f);
			
			// 首次登录邮件
			List<ZcMail> zms = findUseZcMail(1);
			if (zms != null & zms.size() > 0)
			{
				for (ZcMail zcMail : zms)
				{
					Mail mail = Mail.createMail(player.getId(), "GM", zcMail.getTitle(), zcMail.getContent(), zcMail.getReward1(), zcMail.getReward2(), zcMail.getReward3(), zcMail.getReward4(), zcMail.getReward5(), zcMail.getReward6(), zcMail.getGold(), zcMail.getCrystal(), zcMail.getRuneNum(), zcMail.getPower(), zcMail.getFriendNum(), zcMail.getDeleteTime());
					session.save(mail);
				}
			}
			
			session.update(player);
			ts.commit();
			return player.getId();
		}
		catch (Exception e)
		{
			ts.rollback();
			dbLogger.error("注册出错,uid:" + uid + ",psd:" + psd, e);
		}
		finally
		{
			session.close();
		}
		return 0;
	}
	
	/** 加载event表 **/
	@SuppressWarnings("unchecked")
	public List<Event> getEvents()
	{
		Session session = getSession();
		try
		{
			// 获取event
			String hql = "from Event e";
			Query query = session.createQuery(hql);
			List<Event> events = query.list();
			if (events.size() <= 0)
			{
				return null;
			}
			else
			{
				return events;
			}
		}
		catch (Exception e)
		{
			dbLogger.error("查询event出错", e);
		}
		finally
		{
			session.close();
		}
		return null;
	}
	
	/** 保存event信息 **/
	public void saveEvent(Event event)
	{
		Session session = getSession();
		Transaction ts = session.beginTransaction();
		try
		{
			session.saveOrUpdate(event);
			logger.info("save event completed");
			ts.commit();
		}
		catch (Exception e)
		{
			dbLogger.error("保存event信息出错", e);
			ts.rollback();
		}
		finally
		{
			session.close();
		}
	}
	
	/** 保存mail信息 **/
	public void saveMail(Mail m)
	{
		Session session = getSession();
		Transaction ts = session.beginTransaction();
		try
		{
			session.save(m);
			ts.commit();
			logger.info("save mail completed");
		}
		catch (Exception e)
		{
			dbLogger.error("保存mail信息出错", e);
			ts.rollback();
		}
		finally
		{
			session.close();
		}
	}
	
	/** 批量保存mail信息 **/
	public void batchSaveMail(List<Mail> mails)
	{
		Session session = getSession();
		Transaction ts = session.beginTransaction();
		try
		{
			for (Mail mail : mails)
			{
				session.save(mail);
			}
			ts.commit();
			logger.info("batch save mail completed");
		}
		catch (Exception e)
		{
			dbLogger.error("批量保存mail信息出错", e);
			ts.rollback();
		}
		finally
		{
			session.close();
		}
	}
	
	/** 删除邮件 **/
	@SuppressWarnings("deprecation")
	public int removeMails()
	{
		Session session = getSession();
		Transaction ts = session.beginTransaction();
		try
		{
			String sql = "UPDATE mail SET STATE=1 WHERE STATE!=1 and (" + System.currentTimeMillis() + "-SENDTIME >= DELETETIME*60*1000)";
			Connection conn = session.connection();
			PreparedStatement ps = conn.prepareStatement(sql);
			int num = ps.executeUpdate();
			ts.commit();
			ps.close();
			conn.close();
			return num;
		}
		catch (Exception e)
		{
			dbLogger.error("删除mail信息出错", e);
			ts.rollback();
			return 0;
		}
		finally
		{
			session.close();
		}
	}
	
	/** 加载activity **/
	@SuppressWarnings("unchecked")
	public List<Activity> getActivitys()
	{
		Session session = getSession();
		try
		{
			// 获取event
			String hql = "from Activity a";
			Query query = session.createQuery(hql);
			List<Activity> activitys = query.list();
			if (activitys.size() <= 0)
			{
				return null;
			}
			else
			{
				return activitys;
			}
		}
		catch (Exception e)
		{
			dbLogger.error("查询activity出错", e);
		}
		finally
		{
			session.close();
		}
		return null;
	}
	
	public void savePayRecord(PayRecord pr)
	{
		Session session = getSession();
		Transaction ts = session.beginTransaction();
		try
		{
			session.save(pr);
			ts.commit();
		}
		catch (Exception e)
		{
			ts.rollback();
			dbLogger.error("保存支付信息出错", e);
		}
		finally
		{
			session.close();
		}
	}
	
	@SuppressWarnings("deprecation")
	public int getOnePay(int playerId, String startTime, String endTime, int excetPayRecordId)
	{
		if (startTime == null || "".equals(startTime) || endTime == null || "".equals(endTime))
		{
			return 0;
		}
		int result = 0;
		Session session = getSession();
		try
		{
			String sql = "SELECT COST FROM payrecord WHERE PLAYERID=? AND PAYDATE>=? AND PAYDATE<=? AND ID=?";
			Connection conn = session.connection();
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setInt(1, playerId);
			ps.setString(2, startTime);
			ps.setString(3, endTime);
			ps.setInt(4, excetPayRecordId);
			ResultSet rs = ps.executeQuery();
			while (rs.next())
			{
				result = rs.getInt(1);
			}
			rs.close();
			ps.close();
			conn.close();
		}
		catch (Exception e)
		{
			dbLogger.error("查询支付信息出错", e);
		}
		finally
		{
			session.close();
		}
		return result;
	}
	
	@SuppressWarnings("deprecation")
	public int getPayTotal(int playerId, String startTime, String endTime, int excetPayRecordId)
	{
		if (startTime == null || "".equals(startTime) || endTime == null || "".equals(endTime))
		{
			return 0;
		}
		int result = 0;
		Session session = getSession();
		try
		{
			String sql = "SELECT SUM(COST) FROM payrecord WHERE PLAYERID=? AND PAYDATE>=? AND PAYDATE<=? AND ID!=?";
			Connection conn = session.connection();
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setInt(1, playerId);
			ps.setString(2, startTime);
			ps.setString(3, endTime);
			ps.setInt(4, excetPayRecordId);
			ResultSet rs = ps.executeQuery();
			while (rs.next())
			{
				result = rs.getInt(1);
			}
			rs.close();
			ps.close();
			conn.close();
		}
		catch (Exception e)
		{
			dbLogger.error("查询支付信息出错", e);
		}
		finally
		{
			session.close();
		}
		return result;
	}
	
	@SuppressWarnings("deprecation")
	public int getPayTotal(int playerId)
	{
		int result = 0;
		Session session = getSession();
		try
		{
			String sql = "SELECT SUM(COST) FROM payrecord WHERE PLAYERID=?";
			Connection conn = session.connection();
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setInt(1, playerId);
			ResultSet rs = ps.executeQuery();
			while (rs.next())
			{
				result = rs.getInt(1);
			}
			rs.close();
			ps.close();
			conn.close();
		}
		catch (Exception e)
		{
			dbLogger.error("查询支付信息出错", e);
		}
		finally
		{
			session.close();
		}
		return result;
	}
	
	/** 根据类型获取特殊邮件 **/
	@SuppressWarnings("unchecked")
	public List<SpeciaMail> getSpeciaMails(int type)
	{
		Session session = getSession();
		try
		{
			String sql = "from SpeciaMail sm where sm.type=? and sm.state=1 order by sm.value DESC";
			Query query = session.createQuery(sql);
			query.setInteger(0, type);
			return query.list();
		}
		catch (RuntimeException e)
		{
			dbLogger.error("查询特殊邮件出错", e);
		}
		finally
		{
			session.close();
		}
		return null;
	}
	
	/** 获取需要定时发的特殊邮件 **/
	@SuppressWarnings("unchecked")
	public List<SpeciaMail> getSpeciaMailsBindTime()
	{
		Session session = getSession();
		try
		{
			String sql = "from SpeciaMail sm where sm.type in(11,12) and sm.state=1 order by sm.value DESC";
			Query query = session.createQuery(sql);
			return query.list();
		}
		catch (RuntimeException e)
		{
			dbLogger.error("查询特殊邮件出错", e);
		}
		finally
		{
			session.close();
		}
		return null;
	}
	
	@SuppressWarnings("unchecked")
	public List<SpeciaMail> getSpeciaMails()
	{
		Session session = getSession();
		try
		{
			String sql = "from SpeciaMail sm";
			Query query = session.createQuery(sql);
			return query.list();
		}
		catch (RuntimeException e)
		{
			dbLogger.error("查询特殊邮件出错", e);
		}
		finally
		{
			session.close();
		}
		return null;
	}
	
	public void saveSpeciaMail(SpeciaMail speciaMail)
	{
		Session session = getSession();
		Transaction ts = session.beginTransaction();
		try
		{
			session.save(speciaMail);
			ts.commit();
		}
		catch (Exception e)
		{
			ts.rollback();
			dbLogger.error("保存特殊邮件出错", e);
		}
		finally
		{
			session.close();
		}
	}
	
	public void deleteSpeciaMail(SpeciaMail speciaMail)
	{
		Session session = getSession();
		Transaction ts = session.beginTransaction();
		try
		{
			session.delete(speciaMail);
			ts.commit();
		}
		catch (Exception e)
		{
			ts.rollback();
			dbLogger.error("删除特殊邮件出错", e);
		}
		finally
		{
			session.close();
		}
	}
	
	public void updateSpecialMail(SpeciaMail speciaMail)
	{
		logger.info("updating SpecialMail instance");
		try
		{
			getHibernateTemplate().update(speciaMail);
			logger.info("update SpecialMail successful");
		}
		catch (RuntimeException e)
		{
			dbLogger.debug("update SpecialMail failed", e);
			throw e;
		}
	}
	
	public SpeciaMail one(int id)
	{
		logger.info("find one SpeciaMail instance");
		try
		{
			return (SpeciaMail) getHibernateTemplate().get(SpeciaMail.class, id);
		}
		catch (RuntimeException e)
		{
			dbLogger.debug("find one SpeciaMail failed", e);
			throw e;
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<ZcMail> find()
	{
		try
		{
			return getHibernateTemplate().find("from ZcMail z");
		}
		catch (RuntimeException e)
		{
			dbLogger.debug("find List<ZcMail> failed" + e);
			throw e;
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<ZcMail> findUseZcMail(int type)
	{
		try
		{
			return getHibernateTemplate().find("from ZcMail z where z.state=1 and z.type=" + type);
		}
		catch (RuntimeException e)
		{
			dbLogger.debug("find use zcMail List<ZcMail> failed", e);
			throw e;
		}
	}
	
	public void upZcMailState(ZcMail zcMail)
	{
		try
		{
			getHibernateTemplate().merge(zcMail);
		}
		catch (RuntimeException e)
		{
			dbLogger.debug("update ZcMail failed", e);
			throw e;
		}
	}
	
	public ZcMail oneZcMail(int id)
	{
		try
		{
			return (ZcMail) getHibernateTemplate().get(ZcMail.class, id);
		}
		catch (RuntimeException e)
		{
			dbLogger.debug("find one ZcMail failed", e);
			throw e;
		}
	}
	
	public void delZcMail(ZcMail zcMail)
	{
		try
		{
			getHibernateTemplate().delete(zcMail);
		}
		catch (RuntimeException e)
		{
			dbLogger.debug("del one ZcMail failed", e);
			throw e;
		}
	}
	
	public void saveZcMail(ZcMail zcMail)
	{
		try
		{
			getHibernateTemplate().save(zcMail);
		}
		catch (RuntimeException e)
		{
			dbLogger.debug("save ZcMail failed", e);
			throw e;
		}
	}
	
	/** 获取变量表 **/
	@SuppressWarnings("unchecked")
	public List<Var> getVars()
	{
		Session session = getSession();
		try
		{
			String sql = "from Var";
			Query query = session.createQuery(sql);
			List list = query.list();
			if (list != null && list.size() > 0)
			{
				return list;
			}
		}
		catch (RuntimeException e)
		{
			dbLogger.error("查询变量出错", e);
		}
		finally
		{
			session.close();
		}
		return null;
	}
	
	/** 保存变量 **/
	public void saveVars(List<Var> vars)
	{
		Session session = getSession();
		Transaction ts = session.beginTransaction();
		try
		{
			for (Var var : vars)
			{
				session.saveOrUpdate(var);
			}
			ts.commit();
		}
		catch (RuntimeException e)
		{
			dbLogger.error("保存变量出错", e);
			ts.rollback();
		}
		finally
		{
			session.close();
		}
	}
	
	/** 保存消耗钻石 **/
	public void saveConsumeCrystalLog(ConsumeCrystalLog consumeCrystalLog)
	{
		try
		{
			getHibernateTemplate().save(consumeCrystalLog);
		}
		catch (RuntimeException e)
		{
			dbLogger.debug("save ConsumeCrystalLog failed", e);
			throw e;
		}
	}
	
	/** 获取累计消耗钻石 **/
	@SuppressWarnings("deprecation")
	public int getConsumeCrystalTotal(int id, int playerId, String startTime, String endTime)
	{
		if (startTime == null || startTime.length() <= 0 || endTime == null || endTime.length() <= 0)
		{
			return 0;
		}
		int result = 0;
		Session session = getSession();
		try
		{
			String sql = "SELECT SUM(CRYSTALLOG) FROM gm_crystallog WHERE PLAYERID=? AND LOGDATE>=? AND LOGDATE<=? AND ID!=?";
			Connection conn = session.connection();
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setInt(1, playerId);
			ps.setString(2, startTime);
			ps.setString(3, endTime);
			ps.setInt(4, id);
			ResultSet rs = ps.executeQuery();
			while (rs.next())
			{
				result = rs.getInt(1);
			}
			rs.close();
			ps.close();
			conn.close();
		}
		catch (Exception e)
		{
			dbLogger.debug("find ConsumeCrystalLogs(int id,int playerId,String startTime,String endTime) failed", e);
		}
		finally
		{
			session.close();
		}
		return result;
	}
	
	/** 获取单笔 **/
	@SuppressWarnings("deprecation")
	public int getOneConsumeCrystal(int id, int playerId, String startTime, String endTime)
	{
		if (startTime == null || startTime.length() <= 0 || endTime == null || endTime.length() <= 0)
		{
			return 0;
		}
		int result = 0;
		Session session = getSession();
		try
		{
			String sql = "SELECT CRYSTALLOG FROM gm_crystallog WHERE PLAYERID=? AND LOGDATE>=? AND LOGDATE<=? AND ID=?";
			Connection conn = session.connection();
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setInt(1, playerId);
			ps.setString(2, startTime);
			ps.setString(3, endTime);
			ps.setInt(4, id);
			ResultSet rs = ps.executeQuery();
			while (rs.next())
			{
				result = rs.getInt(1);
			}
			rs.close();
			ps.close();
			conn.close();
		}
		catch (Exception e)
		{
			dbLogger.debug("find OneConsumeCrystalLog(int id,int playerId,String startTime,String endTime) failed" + e);
		}
		finally
		{
			session.close();
		}
		return result;
	}
	
	/** 保存购买日志 **/
	public void saveLogbuys(List<LogBuy> logs)
	{
		Session session = getSession();
		Transaction ts = session.beginTransaction();
		try
		{
			for (LogBuy log : logs)
			{
				session.saveOrUpdate(log);
			}
			ts.commit();
		}
		catch (Exception e)
		{
			dbLogger.error("保存购买日志出错", e);
			ts.rollback();
		}
		finally
		{
			session.close();
		}
	}
	
	public void saveEventDrop(EventDrop eventDrop)
	{
		try
		{
			getHibernateTemplate().save(eventDrop);
		}
		catch (RuntimeException e)
		{
			dbLogger.debug("save EventDrop failed", e);
			throw e;
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<EventDrop> findEventDrops()
	{
		try
		{
			return getHibernateTemplate().find("from EventDrop e");
		}
		catch (RuntimeException e)
		{
			dbLogger.debug("find All EventDrop failed", e);
			throw e;
		}
	}
	
	public void margeEventDrop(EventDrop eventDrop)
	{
		try
		{
			getHibernateTemplate().merge(eventDrop);
		}
		catch (RuntimeException e)
		{
			dbLogger.debug("merge one EventDrop failed", e);
			throw e;
		}
	}
	
	public EventDrop findOneEventDrop(int id)
	{
		try
		{
			return (EventDrop) getHibernateTemplate().get(EventDrop.class, id);
		}
		catch (RuntimeException e)
		{
			dbLogger.debug("find one EventDrop failed", e);
			throw e;
		}
	}
	
	public void delEventDrop(EventDrop eventDrop)
	{
		try
		{
			getHibernateTemplate().delete(eventDrop);
		}
		catch (RuntimeException e)
		{
			dbLogger.debug("del one EventDrop failed", e);
			throw e;
		}
	}
	
	/** 存十连抽 **/
	public void saveChouCardLog(LotLog chouCardLog)
	{
		try
		{
			getHibernateTemplate().save(chouCardLog);
		}
		catch (RuntimeException e)
		{
			dbLogger.debug("save one ChouCardLog failed", e);
			throw e;
		}
	}
	
	/** 根据时间查询十连抽 **/
	@SuppressWarnings("deprecation")
	public int getChouCardLogByDate(int id, int playerId, String startTime, String endTime)
	{
		if (startTime == null || startTime.length() <= 0 || endTime == null || endTime.length() <= 0)
		{
			return 0;
		}
		int result = 0;
		Session session = getSession();
		try
		{
			String sql = "SELECT SUM(SHILIANCHOUNUM) FROM gm_lotlog WHERE PLAYERID=? AND LOGDATE>=? AND LOGDATE<=? AND ID!=?";
			Connection conn = session.connection();
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setInt(1, playerId);
			ps.setString(2, startTime);
			ps.setString(3, endTime);
			ps.setInt(4, id);
			ResultSet rs = ps.executeQuery();
			while (rs.next())
			{
				result = rs.getInt(1);
			}
			rs.close();
			ps.close();
			conn.close();
		}
		catch (Exception e)
		{
			dbLogger.debug("根据时间查询十连抽出错!", e);
		}
		finally
		{
			session.close();
		}
		return result;
	}
	
	/** 存ko积分log **/
	public void saveKopointLog(KopointLog kopointLog)
	{
		try
		{
			getHibernateTemplate().save(kopointLog);
		}
		catch (RuntimeException e)
		{
			dbLogger.debug("save one KopointLog failed", e);
			throw e;
		}
	}
	
	/** 根据时间查询Ko积分log **/
	@SuppressWarnings("deprecation")
	public int getKopointLogByDate(int id, int playerId, String startTime, String endTime)
	{
		if (startTime == null || startTime.length() <= 0 || endTime == null || endTime.length() <= 0)
		{
			return 0;
		}
		int result = 0;
		Session session = getSession();
		try
		{
			String sql = "SELECT SUM(kopointNum) FROM gm_kopointlog WHERE PLAYERID=? AND LOGDATE>=? AND LOGDATE<=? AND ID!=?";
			Connection conn = session.connection();
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setInt(1, playerId);
			ps.setString(2, startTime);
			ps.setString(3, endTime);
			ps.setInt(4, id);
			ResultSet rs = ps.executeQuery();
			while (rs.next())
			{
				result = rs.getInt(1);
			}
			rs.close();
			ps.close();
			conn.close();
		}
		catch (Exception e)
		{
			dbLogger.debug("find KopointLog By Date failed", e);
		}
		finally
		{
			session.close();
		}
		return result;
	}
	
	/** 查询玩家抽卡排行 **/
	@SuppressWarnings("unchecked")
	public List<LotRank> getLotRanks()
	{
		try
		{
			//return getHibernateTemplate().find("from LotRank l order by l.score desc,l.lastLotTime asc LIMIT 0,20");
			return getHibernateTemplate().find("from LotRank l order by l.score desc,l.lastLotTime asc");
		}
		catch (RuntimeException e)
		{
			dbLogger.debug("find getLotRanks failed", e);
			throw e;
		}
	}
	
	/** 保存玩家抽卡排行信息 **/
	public void saveLotRanks(Collection<LotRank> lrs)
	{
		Session session = getSession();
		Transaction ts = session.beginTransaction();
		try
		{
			for (LotRank lr : lrs)
			{
				session.saveOrUpdate(lr);
			}
			logger.info("save lrs completed");
			ts.commit();
		}
		catch (Exception e)
		{
			dbLogger.error("保存抽卡排名出错", e);
			ts.rollback();
		}
		finally
		{
			session.close();
		}
	}
	
	/** 清空玩家抽卡排行信息 **/
	public void delLotRanks()
	{
		Session session = getSession();
		Transaction ts = session.beginTransaction();
		try
		{	

			Query q = session.createQuery("delete from LotRank");
			q.executeUpdate();
			ts.commit();
		}
		catch (Exception e)
		{
			ts.rollback();
			dbLogger.error("清空玩家限时神将排行",e);
		}
		finally
		{
			session.close();
		}
	}
	/**清空玩家大风车活动数据**/
	public void delActiviDFC(int playerId)
	{
		Session session = getSession();
		Transaction ts = session.beginTransaction();
		try
		{
			Query q = session.createQuery("update Player p set p.lottoTimes='',p.lottoReward='',p.lottoTurnTimes='',p.LastLottoAward='' where p.id=?");
			q.setInteger(0, playerId);
			q.executeUpdate();
			ts.commit();
		}
		catch (Exception e)
		{
			ts.rollback();
			dbLogger.error("清空玩家大风车活动数据",e);
		}
		finally
		{
			session.close();
		}
	}
	/**清空迷宫进度**/
	public void delMaze()
	{
		Session session = getSession();
		Transaction ts = session.beginTransaction();
		try
		{	
			Query q = session.createQuery("delete from Maze");
			q.executeUpdate();
			ts.commit();
		}
		catch (Exception e)
		{
			ts.rollback();
			dbLogger.error("清空每天迷宫进度",e);
		}
		finally
		{
			session.close();
		}
	}
}
